<?php

namespace App\Http\Controllers\V1\BasicData;

use App\Http\Requests\V1\CollegesRequest;
use App\Models\V1\Colleges;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
class CollegesController extends Controller
{
    /**
     * 显示校区数据管理页面
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('v1.colleges');
    }

    /**
     * 获取校区数据
     *
     * @param Request $request
     */
    public function postIndex(Request $request)
    {
        $response = [
            'code' => 1,
            'msg' => '',
            'count' => 0,
            'data' => [],
        ];

        // 获取符合查询条件的年级数据
        $currentPage = $request->get('page');
        $rows = $request->get('limit');
        $keywords = $request->get('keywords');

        // 获取符合查询条件的年级数据
        $data = $this->getCollegeList($currentPage, $rows, $keywords);

        if (!$data->isEmpty()) {

            $formatList = array();

            $count = $data->total() > 0 ? $data->total() : 0;

            if ($count > 0) {
                // 格式化数据
                foreach ($data->items() as $item) {
                    $formatItem['code'] = $item['code'];
                    $formatItem['name'] = $item['name'];
                    $formatItem['address'] = $item['address'];
                    $formatItem['longitude'] = $item['longitude'];
                    $formatItem['latitude'] = $item['latitude'];
                    $formatItem['updated_at'] = $item['updated_at']->format('Y-m-d H:i:s');
                    $formatItem['created_at'] = $item['created_at']->format('Y-m-d H:i:s');
                    array_push($formatList, $formatItem);
                }

                $response['code'] = 0;
                $response['msg'] = '加载数据成功';
                $response['count'] = $count;
                $response['data'] = $formatList;
            }
        }

        return $response;
    }

    /**
     * 进入单条校区数据显示界面（适用于查看viewData功能）
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showView(Request $request)
    {

        $data['view'] = $request->input('view');
        switch ($request->input('view')) {
            case 'addData':
                return view('v1.form.colleges_item', $data);
                break;
            case 'viewData':
                $code = $request->input('code');
                $data['itemData'] = $this->getCollegeByCode($code);
                return view('v1.form.colleges_item', $data);
                break;
            default:
                break;
        }
    }

    /**
     * 显示校区数据导入页面
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function importView(Request $request)
    {
        // 获取登录用户
        $loginUser = Auth::user();

        $data['view'] = $request->input('view');
        $data['code'] = $loginUser['code'];

        return view('v1.form.upload_excel', $data);
    }

    /**
     * 更新校区基本信息(单元格)
     *
     * @param CollegesRequest $request
     * @return array
     */
    public function updateCellData(CollegesRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '校区代码[' . $request->input('code') . '],更新失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateColleges($request);

            // 更新年级信息
            $successFlag = $this->handleUpdate($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '校区代码[' . $request->input('code') . '],更新成功！';
            }
        }

        return $response;
    }

    /**
     * 新增基本信息
     *bail关键字表示只要第一个验证失败后面就不验了，提高效率
     * @param Request $request
     * @return array
     */
    public function addData(Request $request)
    {
        $code = $request->input('code');
        $response = [
            'rspStatus' => false,
            'rspMsg' => '校区[' . $code . '],新增失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $rules['code'] = 'bail|required';
            $rules['captcha'] = 'bail|required|captcha';
            $messages['code.required'] = '校区代码不能为空';
            $messages['captcha.captcha'] = '验证码错误';
            $this->validate($request, $rules, $messages);

            // 新增信息
            $successFlag = $this->handleAdd($request);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '校区[' . $code . '],新增成功！';
            }
        }
        return $response;
    }


    /**
     * 删除校区基本信息
     *
     * @param CollegesRequest $request
     * @return array
     */
    public function deleteData(CollegesRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '校区代码[' . $request->input('code') . '],删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateColleges($request);

            // 删除年级信息
            $successFlag = $this->handleDelete($request, false);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '校区代码[' . $request->input('code') . '],删除成功！';
            }
        }

        return $response;
    }

    /**
     * 批量删除校区基本信息
     *
     * @param Request $request
     * @return array
     */
    public function deleteBatchData(Request $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '校区批量删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 删除校区信息
            $successFlag = $this->handleDelete($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '校区批量删除成功！';
            }
        }

        return $response;
    }

    ///////////////////////////////////////////////////////////////////
    /// 获取数据功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 分页查询符合条件的校区列表数据
     *
     * @param int $page 当前页数
     * @param $rows 每页显示条数
     * @param $keywords 搜索关键词
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator 分页对象
     */
    private function getCollegeList($page = 1, $rows, $keywords)
    {
        if (!isset($keywords) || empty($keywords)) {
            $data = Colleges::orderBy('id', 'asc')->paginate($rows, ['*'], 'page', $page);
        } else {
            $data = Colleges::where('name', 'like', '%' . $keywords . '%')->orderBy('id', 'asc')
                ->paginate($rows, ['*'], 'page', $page);
        }
        return $data;
    }

    /**
     * 根据校区代码获取对应校区信息
     *
     * @param $code
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    private function getCollegeByCode($code)
    {
        $Colleges = Colleges::where('code', $code)->first();
        return $Colleges;
    }

    ///////////////////////////////////////////////////////////////////
    /// 验证表单功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理新增、更新校区信息验证请求
     *
     * @param CollegesRequest $request
     */
    private function validateColleges(CollegesRequest $request)
    {
        $rules = $request->rules();
        if ($request->input("captcha") !== null) {
            $rules['captcha'] = 'bail|required|captcha';
        }
        $messages = $request->messages();
        // 执行表单数据验证
        $this->validate($request, $rules, $messages);
    }

    ///////////////////////////////////////////////////////////////////
    /// 业务逻辑处理功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理更新校区信息
     *
     * @param Request $request
     * @param bool $bCell 是否为单元格修改数据
     * @return bool
     */
    private function handleUpdate(Request $request, $bCell)
    {
        $where = $request->input('code');

        if ($bCell) { // 单元格修改
            $attrs = $request->input('attrs');
            $values = $request->input('values');
            // 拼装更新数据数组
            $updateData = array();
            $counter = 0;
            foreach ($attrs as $attr) {
                $updateData[$attr] = $values[$counter];
                $counter++;
            }
        } else { // 表单修改
            // 拼装更新数据数组
            $updateData = [
                'name' => $request->input('name'),
            ];
        }

        $rspObj = Colleges::where('code', $where)->update($updateData);

        return $rspObj;
    }


    /***
     * 新增处理
     * @param Request $request
     * @return mixed
     */
    public function handleAdd(Request $request) {
        $code = $request->input('code');
        // 拼装新增数据数组
        $insertData = [
            'code' => $code,
            'name' => $request->input('name'),
            'address' => $request->input('address'),
            'longitude' => $request->input('longitude'),
            'latitude' => $request->input('latitude'),
        ];
        $rspObj = Colleges::create($insertData);
        return $rspObj;
    }

    /**
     * 处理删除校区信息
     *
     * @param Request $request
     * @param bool $bBatch 是否为批量数据
     * @return bool
     */
    private function handleDelete(Request $request, $bBatch)
    {
        $where = $request->input('code');

        if ($bBatch) { // 批量删除
            foreach ($where as $code) {
                $rspObj = Colleges::where('code', $code)->delete();
            }
        } else { // 单条删除
            $rspObj = Colleges::where('code', $where)->delete();
        }

        return $rspObj;
    }
}
